<template>
  <div class="map-detail-dialog">
    <VideoMapPopup v-if="currentType == 'sxj' || currentType == 'jjj-sxj'" ref="videoMapPopup">
      <template v-slot:title>
        <span class="title-name" :title="currentData.titleName || currentData.name">
          {{ currentData.titleName || currentData.name }}
        </span>
      </template>

      <template v-slot:main>
        <!--摄像头-->
        <div class="bounced-content">
          <VideoPlayer :url="videoUrl"></VideoPlayer>
        </div>
      </template>
    </VideoMapPopup>

    <TrafficMapPopup ref="mapPopupDialog" v-else>
      <template v-slot:title>
        <span class="title-name" :title="currentData.titleName || currentData.name">{{
          currentData.titleName || currentData.name
        }}</span>
      </template>

      <template v-slot:main>
        <!--摄像头-->
        <div class="bounced-content" v-if="currentType == 'sxj' || currentType == 'jjj-sxj'">
          <VideoPlayer :url="videoUrl"></VideoPlayer>
        </div>

        <!-- 情报板 -->
        <div class="bounced-content information-board" v-else-if="currentType == 'qbb'">
          <div :style="{ color: QBB_COLOR[informationBoardText && informationBoardText.color] || '#05da05' }">
            {{ informationBoardText && informationBoardText.message }}
          </div>
        </div>

        <!-- 交调点 -->
        <div class="bounced-content" v-else-if="currentType == 'jdd'">
          <a-radio-group v-model:value="directionActive" button-style="solid" @change="getHandDetail(currentData)">
            <a-radio-button value="1">上行</a-radio-button>
            <a-radio-button value="2">下行</a-radio-button>
          </a-radio-group>
          <div v-if="jddLoading" class="jdd-loading-wrapper">
            <a-spin size="large" />
          </div>

          <div class="hand-chart" v-else>
            <LineChart :seriesData="flowSeriesData" title="断面流量" :xDate="xDate" :typeArr="typeArr" />
            <LineChart :seriesData="speedSeriesData" title="平均车速" :xDate="xDate" :typeArr="typeArr" />
          </div>
        </div>

        <!-- 交通管制弹框 -->
        <div
          class="bounced-content traffic-control"
          v-else-if="currentData.eventType == 'JGB1' && currentType == 'dlsj'"
        >
          <div class="control-top">
            <div class="control-road">
              <span class="control-city"></span>
              <span class="control-road-name">
                <span>
                  {{
                    controlDetail.trafficIntoArr &&
                    controlDetail.trafficIntoArr[0] &&
                    controlDetail.trafficIntoArr[0].croadcid
                  }}
                </span>
                <span>{{
                  controlDetail.trafficIntoArr &&
                  controlDetail.trafficIntoArr[0] &&
                  controlDetail.trafficIntoArr[0].closereasontext
                }}</span>
              </span>
            </div>
            <div class="control-flex">
              <span class="control-title">{{
                controlDetail.trafficIntoArr &&
                controlDetail.trafficIntoArr[0] &&
                controlDetail.trafficIntoArr[0].tsname
              }}</span>
              <span class="control-text">{{ controlDetail.closereasonText }}</span>
            </div>
          </div>

          <div class="control-bottom">
            <div class="control-exit">
              <span
                class="control-exit-colse"
                :style="{
                  color:
                    controlDetail.trafficOutArr &&
                    controlDetail.trafficOutArr[0] &&
                    controlDetail.trafficOutArr[0].infotype == 1
                      ? 'red'
                      : '#00FF18'
                }"
                >{{
                  controlDetail.trafficOutArr &&
                  controlDetail.trafficOutArr[0] &&
                  controlDetail.trafficOutArr[0].infotype == 1
                    ? '出口关闭'
                    : '出口开启'
                }}</span
              >
            </div>
            <div class="control-entrance">
              <div v-for="(val, ind) in controlDetail.trafficIntoArr" class="control-entrance-box" :key="ind">
                <span class="control-entrance-colse" :style="{ color: val.infotype == 1 ? 'red' : '#00FF18' }">{{
                  val.infotype == 1 ? '入口关闭' : '入口开启'
                }}</span>
                <span class="control-entrance-direction">{{ val.direction ? val.direction + '方向' : '' }}</span>
              </div>
            </div>
          </div>
        </div>

        <!--桥面监测 、红绿灯管控 弹框-->
        <div class="bounced-content" v-else-if="currentType == 'qmjc' || currentType == 'hld'">
          <iframe :src="bridgeUrl" style="width: 100%; height: 100%" frameborder="0"></iframe>
          <span class="img-big" @click="popupChange">
            <img src="@/views/business-component/assets/images/bridge-big.png" alt="" />
          </span>
        </div>
        <!-- 路网事件、疫情防控 -->
        <div class="bounced-content" v-else>
          <div class="describe" v-for="(item, index) in pointDetail" :key="index">
            <span class="name">{{ item.title }}</span>
            <span class="value">{{ item.value }}</span>
          </div>
        </div>
      </template>
    </TrafficMapPopup>
  </div>
</template>

<script setup>
/**
 * 地图通用弹框
 * @author 阳坤（1194636148@qq.com）
 * @date   时间：2022/5/26
 */

import TrafficMapPopup from './TrafficMapPopup.vue'
import VideoMapPopup from './VideoMapPopup.vue'
import VideoPlayer from '@/components/video-player/VideoPlayer'
import baseServiceApi from '../../../api/base-service.js'
import eventApi from '../../../api/event.js'
import trafficApi from '../../../api/traffic'
import * as authApi from '@/api/auth'
import LineChart from '../../../components/charts/ShadowLine.vue'
import { filterMapDialogDetail } from '../lib/map-dialog-detail.js'
import { filterEventDetail } from '../../event-detail/details'
import { ref, defineProps, defineEmits, defineExpose, onBeforeUnmount, getCurrentInstance, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { get } from '@/utils'
import { useStore } from 'vuex'
import Cookies from 'js-cookie'

const QBB_COLOR = {
  255000000: 'red',
  '000255000': 'green',
  255255000: 'yellow'
}

const props = defineProps({
  // 数据类型
  currentType: {
    type: String,
    default: ''
  },
  // 数据项
  currentData: {
    type: Object,
    default: () => {}
  }
})
const store = useStore()
const { proxy } = getCurrentInstance()

const emit = defineEmits(['cameraClose'])
// 通用弹框ref
const mapPopupDialog = ref()
// 摄像头弹框ref
const videoMapPopup = ref()
// 视频弹框url
const videoUrl = ref()

// 当前情报板所展示内容
const informationBoardText = ref()
// 情报板内容集合
const informationBoardArr = ref([])
// 情报板定时器
const boardTimer = ref(null)
const pointDetail = ref({})
// 交通管制详情
const controlDetail = ref({})
const controlArr = ref([]) // 交通管制经纬度列表所有数据集
// 交调点详情
const observation = ref({})
const jddLoading = ref(false)
// 交调点按钮选中项
const directionActive = ref('1')
// 折线图数据
const xDate = ref([])
const typeArr = ref(['预测上限', '预测下限', '观察数值'])
// 交调点流量折线数据
const flowSeriesData = ref([
  {
    name: '预测上限',
    color: '#fe3636',
    data: []
  },
  {
    name: '预测下限',
    color: '#16ade1',
    data: []
  },
  {
    name: '观察数值',
    color: '#4fce8e',
    data: []
  }
])
// 交调点速度折线数据
const speedSeriesData = ref([
  {
    name: '预测上限',
    color: '#fe3636',
    data: []
  },
  {
    name: '预测下限',
    color: '#16ade1',
    data: []
  },
  {
    name: '观察数值',
    color: '#4fce8e',
    data: []
  }
])

// 桥面监测弹框url
const bridgeUrl = ref()
// 桥面监测点位数据
const bridgeList = ref({})
// 桥面监测弹框放大缩小
const bridgeFlag = ref(true)

onMounted(() => {
  // 获取交通管制所有经纬度储存
  getControlLonLatitude()
})

/**
 * 显示弹框
 */
const showPopup = (type, data) => {
  hidePopup() // 关闭弹框
  if (!type || !data.path) return
  if (data.path.constructor === Object) {
    data.path = [data.lng, data.lat]
  }

  pointDetail.value = []

  // 摄像头
  if (type == 'sxj') {
    return getCameraUrl(data)
  }
  // 情报板
  if (type == 'qbb') {
    return getInformationBoard(data)
  }

  // 高速道路事件
  if (type == 'dlsj') {
    if (data.eventType == 'JGB1') {
      return getTrafficControlDetail(data, type)
    } else {
      return getEventDetail(data, type)
    }
  }
  // 公路/高速 事件
  if (type == 'glsjcz') {
    return getHighwayEventDetail(data, type)
  }
  // 交调点
  if (type == 'jdd') {
    return getHandDetail(data)
  }
  // 疫情防控
  if (type == 'yqfk') {
    return getEpidemicDetail(data, type)
  }
  // 交建局事件（临时存在）
  if (type == 'jjjsg') {
    setTimeout(() => {
      pointDetail.value = props.currentData.detail
      mapPopupDialog.value.showPopup(400, 280, 'dialog-blue', data.path, [
        Number(data.path[0]),
        Number(data.path[1]) // - 0.015
      ])
    })
  }

  // 高速门架
  if (type == 'gs-mj') {
    mapPopupDialog.value.showPopup(450, 250, 'dialog-blue', data.path, [
      Number(data.path[0]),
      Number(data.path[1]) - 0.015
    ])
  }

  // 施工摄像机
  if (type == 'jjj-sxj') {
    videoUrl.value = data.url
    videoMapPopup.value.showPopup(400, 225, 'dialog-blue', data.path, [
      Number(data.path[0]),
      Number(data.path[1]) - 0.015
    ])
  }

  // 桥面监测、红绿灯管控
  if (type == 'qmjc' || type == 'hld') {
    bridgeList.value = data
    return getBridgeDetail(data, type)
  }
}

/**
 * 获取摄像头
 * @param   data   数据对象
 */
const getCameraUrl = data => {
  const params = {
    cameraId: data.cameraId,
    roadType: data.roadType,
    videoType: 1
  }
  baseServiceApi
    .getCameraUrl(params)
    .then(res => {
      if (res.detail) {
        videoUrl.value = res.detail
        videoMapPopup.value.showPopup(data.roadType == 1 ? 276 : 400, 225, 'dialog-blue', data.path, [
          Number(data.path[0]),
          Number(data.path[1]) - 0.015
        ])
      } else {
        message.warning('摄像机暂无数据')
        videoMapPopup.value.close()
      }
    })
    .catch(e => {
      message.error('摄像机加载失败！')
      videoMapPopup.value.close()
    })
}

/**
 * 获取高速事件详情
 * @param   data   数据对象
 */
const getEventDetail = (data, type) => {
  const params = {
    eventId: data.eventId,
    eventType: data.eventType
  }
  eventApi
    .getEventDetails(params)
    .then(res => {
      if (res.data) {
        const arr = filterEventDetail(res.data, data.eventType)
        pointDetail.value = [arr[0], arr[2], arr[3], arr[6]]
        mapPopupDialog.value.showPopup(400, 240, 'dialog-blue', data.path, [
          Number(data.path[0]),
          Number(data.path[1]) - 0.015
        ])
      } else {
        message.warning('路网事件暂无数据')
        mapPopupDialog.value.close()
      }
    })
    .catch(e => {
      message.error('路网事件加载失败！')
      mapPopupDialog.value.close()
    })
}

/**
 * 获取公路事件详情   公路高速
 * @param   data   数据对象
 */
const getHighwayEventDetail = (data, type) => {
  // // 计划性画线
  // if (['JEA1', 'JFA1', 'TBA1', 'JGA1', 'JEB1', 'TBB1', 'JGB1'].includes(data.customEventType) && !data.lineString) {
  //   proxy
  //     .$mapSdk()
  //     .getLineLatLonList({ text: data.name, lineColor: '#fcb42d' }, data.lineParams)
  //     .then(res => {
  //       // 画线
  //       proxy.$mapSdk().createMvMapLineLayer(res, (e, data) => {})
  //     })
  // }
  // 获取方向
  const params = {
    manageRangeId: data.eventPositionList[0].roadSectionId,
    bussinessCode: get(store.state, 'user.bussinessType')
    // deptId: data.eventPositionList[0].jurisdictionId
  }
  authApi
    .getUnitJurisdiction(params)
    .then(res => {
      if (!get(data, 'eventPositionList.0.roadSectionId')) throw new Error('no roadSectionId')
      if (res.data && res.data.length) {
        data.detail.filter(i => i.title == '方向：')[0].value = get(res, 'data.0.roadDirectionName')
      }
    })
    .finally(() => {
      pointDetail.value = data.detail
      mapPopupDialog.value.showPopup(400, 280, 'dialog-blue', data.path, [Number(data.path[0]), Number(data.path[1])])
    })
}

/**
 * 高速道口（交通管制）事件
 * @param   data   数据对象
 */
const getTrafficControlDetail = (data, type) => {
  eventApi.getStationOperationDetail(data.tsname).then(res => {
    if (res.data && res.data.length) {
      // 得到高速交通管制弹框详情
      controlDetail.value = filterMapDialogDetail([res.data, controlArr.value], type)
      mapPopupDialog.value.showPopup(500, 250, 'dialog-red', data.path)
    }
  })
}

/**
 * 获取情报板
 * @param   data   数据对象
 */
const getInformationBoard = data => {
  if (boardTimer.value) {
    clearInterval(boardTimer.value)
    boardTimer.value = null
  }
  const params = {
    informationId: data.id || data.vmsId,
    roadType: data.roadType,
    ledType: data.vmsType || null
  }
  informationBoardArr.value = []
  baseServiceApi
    .getInformationDetail(params)
    .then(res => {
      if (res.data && res.data.length) {
        informationBoardArr.value = res.data
        mapPopupDialog.value.showPopup(450, 250, 'dialog-blue', data.path, [
          Number(data.path[0]),
          Number(data.path[1]) - 0.015
        ])
        informationBoardText.value = informationBoardArr.value[0]
        let index = 1
        boardTimer.value = setInterval(() => {
          if (index == informationBoardArr.value.length) index = 0
          informationBoardText.value = informationBoardArr.value[index]
          index++
        }, 1000 * 5)
      } else {
        message.warning('情报板暂无数据')
        mapPopupDialog.value.close()
      }
    })
    .catch(e => {
      message.error('情报板加载失败！')
      mapPopupDialog.value.close()
    })
}

/**
 * 获取交调点
 * @param   data   数据对象
 */
const getHandDetail = data => {
  jddLoading.value = true
  observation.value = {}
  xDate.value = []
  flowSeriesData.value[0].data = []
  flowSeriesData.value[1].data = []
  flowSeriesData.value[2].data = []
  speedSeriesData.value[0].data = []
  speedSeriesData.value[1].data = []
  speedSeriesData.value[2].data = []
  if (data.path) {
    mapPopupDialog.value.showPopup(500, 400, 'dialog-blue', data.path, [
      Number(data.path[0]),
      Number(data.path[1]) + 0.01
    ])
  }
  const params = {
    gczbs: data.gczbs,
    xsfx: directionActive.value
  }
  // getJddDetail  getForecastSpeedFlow
  trafficApi
    .getJddDetail(params)
    .then(res => {
      if (res.data) {
        observation.value = res.data
        xDate.value = res.data.timeList
        flowSeriesData.value[0].data = res.data.forecastCapFlow
        flowSeriesData.value[1].data = res.data.forecastLowFlow
        flowSeriesData.value[2].data = res.data.observationsSpeed
        speedSeriesData.value[0].data = res.data.forecastCapSpeed
        speedSeriesData.value[1].data = res.data.forecastLowSpeed
        speedSeriesData.value[2].data = res.data.observationsFlow
      } else {
        message.warning('交调点暂无数据')
        mapPopupDialog.value.close()
      }
      jddLoading.value = false
    })
    .catch(e => {
      jddLoading.value = false
      message.error('交调点加载失败！')
      mapPopupDialog.value.close()
    })
}

/**
 *  疫情防控详情
 * @param   epidemicId
 */
const getEpidemicDetail = (data, type) => {
  baseServiceApi
    .getEpidemicDetail(data.epidemicId)
    .then(res => {
      if (res.data) {
        pointDetail.value = filterMapDialogDetail(res.data, type)
        mapPopupDialog.value.showPopup(400, 225, 'dialog-blue', data.path, [
          Number(data.path[0]),
          Number(data.path[1]) - 0.015
        ])
      } else {
        message.warning('疫情点位暂无数据')
        mapPopupDialog.value.close()
      }
    })
    .catch(e => {
      message.error('疫情点位加载失败！')
      mapPopupDialog.value.close()
    })
}

/**
 * 获取交通管制所有经纬度储存
 */
const getControlLonLatitude = () => {
  eventApi.getStationAllLonLat('32').then(res => {
    if (res.data && res.data.length) {
      controlArr.value = res.data
    }
  })
}

/**
 * 移除弹框
 */
const hidePopup = () => {
  mapPopupDialog.value && mapPopupDialog.value.hidePopup()
  videoMapPopup.value && videoMapPopup.value.hidePopup()
}

/**
 * 桥面监测弹框详情
 */
const getBridgeDetail = (data, type) => {
  const params = {
    phone: Cookies.get('userId')
  }
  if (type == 'qmjc') {
    baseServiceApi
      .getBridgeUrl(params)
      .then(res => {
        window.open(res.detail)
        // bridgeUrl.value = res.detail
        // mapPopupDialog.value.showPopup(550, 500, 'dialog-blue', data.path, [
        //   Number(data.path[0]),
        //   Number(data.path[1]) // - 0.015
        // ])
      })
      .catch(e => {
        message.error('桥面监测点位加载失败！')
        mapPopupDialog.value.close()
      })
  } else {
    baseServiceApi
      .getTrafficLightUrl(params)
      .then(res => {
        window.open(res.detail)
        // bridgeUrl.value = res.detail
        // mapPopupDialog.value.showPopup(550, 500, 'dialog-blue', data.path, [
        //   Number(data.path[0]),
        //   Number(data.path[1]) // - 0.015
        // ])
      })
      .catch(e => {
        message.error('红绿灯管控点位加载失败！')
        mapPopupDialog.value.close()
      })
  }
}

/**
 * 桥面监测弹框放大缩小功能
 */
const popupChange = () => {
  if (bridgeFlag.value == true) {
    bridgeFlag.value = false
    mapPopupDialog.value.showPopup(1100, 1000, 'dialog-blue', bridgeList.value.path, [
      Number(bridgeList.value.path[0]),
      Number(bridgeList.value.path[1]) // - 0.015
    ])
  } else {
    bridgeFlag.value = true
    mapPopupDialog.value.showPopup(550, 500, 'dialog-blue', bridgeList.value.path, [
      Number(bridgeList.value.path[0]),
      Number(bridgeList.value.path[1]) // - 0.015
    ])
  }
}

// 页面销毁   清除定时器
onBeforeUnmount(() => {
  if (boardTimer.value) {
    clearInterval(boardTimer.value)
    boardTimer.value = null
  }
})
// 允许父组件访问
defineExpose({
  showPopup,
  hidePopup
})
</script>

<style scoped lang="less">
.title-name {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

.bounced-content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding-bottom: 5px;

  // 通用详情
  .describe {
    font-size: 12px;
    font-weight: 500;
    color: #333333;
    padding: 6px 10px;
    // .name {
    // }
    // .value {
    // }
  }

  // 情报板
  &.information-board {
    height: 100%;
    width: 100%;
    text-align: center;
    overflow-y: auto;
    font-size: 26px;
    background: #000;
    justify-content: center;

    div {
      padding: 0 30px;
    }
  }

  // 交调点
  .hand-chart {
    flex: 1;
    margin-top: 12px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    overflow: hidden;
  }

  // 交通管制
  &.traffic-control {
    .control-top {
      margin: 0.15rem 0;
      display: flex;

      .control-road {
        height: 0.7rem;
        min-width: 0.7rem;
        text-align: center;
        border-radius: 0.08rem;
        background: #03713f;
        // color: #ffffff;
        /* font-weight: 700; */
        flex-direction: column;
        margin-right: 0.25rem;

        .control-city {
          display: inline-block;
          width: 100%;
          height: 15px;
          color: #000;
          background: #ffc104;
          border-radius: 0.08rem 0.08rem 0 0;
          font-size: 0.16rem;
          font-weight: 800;
          margin-bottom: 1px;
        }

        .control-road-name {
          display: flex;
          flex-direction: column;
          line-height: 0.21rem;
          font-size: 0.2rem;
          color: #fff;

          span:nth-child(2) {
            font-size: 0.14rem;
          }
        }
      }

      .control-flex {
        display: flex;
        flex-direction: column;
        .control-title {
          font-size: 0.24rem;
          font-family: Source Han Sans CN, Source Han Sans CN-Regular;
          font-weight: 400;
          text-align: left;
          // color: #ffffff;
        }
        .control-text {
          font-size: 0.21rem;
          font-family: Source Han Sans CN, Source Han Sans CN-Regular;
          font-weight: 400;
          text-align: left;
          color: #9c9b9b;
        }
      }
    }
    .control-bottom {
      display: flex;
      .control-exit {
        font-size: 0.24rem;
        color: #00ff18;
        width: 25%;
        justify-content: space-around;
        flex-wrap: wrap;
      }
      .control-entrance {
        display: flex;
        width: 75%;
        justify-content: space-around;
        flex-wrap: wrap;
        .control-entrance-box {
          display: flex;
          flex-direction: column;
          text-align: center;
          width: 50%;
          .control-entrance-colse {
            font-size: 0.24rem;
            color: red;
          }
          .control-entrance-direction {
            font-size: 0.2rem;
            font-family: Source Han Sans CN, Source Han Sans CN-Regular;
            font-weight: 400;
            // color: #ffffff;
          }
        }
      }
    }
  }

  .jdd-loading-wrapper {
    flex: 1;
    margin-top: 12px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .img-big {
    width: 28px;
    height: 28px;
    border-radius: 50%;
    background: rgba(0, 0, 0, 0.6);
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    right: 10px;
    bottom: 10px;
    cursor: pointer;
    img {
      width: 15px;
      height: 14px;
    }
  }
}
</style>
